package de.hsowl.tod4a.server;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * Watches for multiple access to files by various thread use.
 * 
 * @author Sebastian Witt
 * 
 */
public class FileWatcher {

	/** Thread safe HashMap */
	public static ConcurrentHashMap<String, Boolean> list = new ConcurrentHashMap<String, Boolean>();

	private static Logger logger = Logger.getLogger(FileWatcher.class);

	/**
	 * Gives permission to enter a file and locks the file for other threads
	 * 
	 * @param f
	 * @return true->access granted;<br>
	 *         false->access denied
	 */
	public static synchronized boolean accessFile(File f) {
		if (f != null) {
			String path = f.getAbsolutePath();

			if (list.get(path) == null) {
				list.put(path, false);
				// logger.debug("File: " + path + " -> access granted");
				return true;
			} else if (list.get(path) == true) {
				list.remove(path);
				list.put(path, false);
				// logger.debug("File: " + path + " -> access granted");
				return true;
			} else if (list.get(path) == false) {
				logger.error("File: " + path + " -> access denied");
				return false;
			}
			logger.error("Error: FileWatcher.accessFile()");
			throw new RuntimeException("FileWatcher");
		} else {
			logger.error("Error: FileWatcher.accessFile() --> file == null");
			throw new NullPointerException("FileWatcher.accessFile() --> file == null");
		}
	}

	/**
	 * Release a file lock. Other threads are now able to access the released
	 * file
	 * 
	 * @param f
	 */
	public static synchronized void releaseFile(File f) {
		if (f != null) {
			String path = f.getAbsolutePath();
			list.remove(path);
			list.put(path, true);
			// logger.debug("File (" + path + ") released");
		} else {
			logger.error("Error: FileWatcher.releaseFile() --> file == null");
			throw new NullPointerException("FileWatcher.releaseFile() --> file == null");
		}
	}
}
